package com.chijun.mform.field.impl;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.field.BaseField;
import com.chijun.mform.field.UpLoadFileListener;

import com.chijun.mform.full.mode.ModeFormFile;
import com.chijun.mform.full.mode.ModeFormFullFileData;
import com.example.ccj.b.c.custom.image.LoadImagesRecycler;
import com.example.ccj.b.c.custom.image.MLocalMedia;
import com.example.ccj.b.c.dialog.DrawingBoardDialog;
import com.example.ccj.u.AdaptScreenUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.sqlite.SqliteExcuteCommand;
import com.example.ccj.u.tengxun.cos.COS;
import com.example.ccj.u.tengxun.cos.CosUploadCallBack;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.ObservableEmitter;

/**
 * 手写
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/23 15:44
 */
public class FieldFor16ShouXie extends BaseField {
    public FieldFor16ShouXie(){
        super();
    }

    @Override
    public View getWritelView(Context context, WriteFormClass writeFormClass) {
        FormField formField = writeFormClass.formField;
        //隐藏输入框
        writeFormClass.fieldFullContentView.setVisibility(View.GONE);

        //宽度最大化字段名
        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams2.weight = 1;
        writeFormClass.fieldFullNameView.setLayoutParams(layoutParams2);

        //手写图片加载view
        ImageView imageView = new ImageView(context);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(AdaptScreenUtils.pt2Px(50),AdaptScreenUtils.pt2Px(50)));
        writeFormClass.fieldFullContentLayout.addView(imageView);

        List<ModeFormFile> formFileModeList1 = SqliteExcuteCommand.get(context, ModeFormFile.class, "sanJiId=?", String.valueOf(formField.getId()));
        if (formFileModeList1 != null && !formFileModeList1.isEmpty()) {
            imageView.post(() -> ImageUtils.loadImage(context, Uri.parse(formFileModeList1.get(0).uri),imageView));
        }

        //打开手写版
        writeFormClass.fieldFullJumpImgView.setVisibility(View.VISIBLE);
        writeFormClass.fieldFullJumpImgView.setImageResource(R.drawable.shen_pi_add_process);
        writeFormClass.fieldFullJumpImgView.setOnClickListener(v -> {
            //获取所有文件的管理权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 先判断有没有权限
                if (!Environment.isExternalStorageManager()) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                    ((Activity) context). startActivityForResult(intent, 100);
                } else {
                    DrawingBoardDialog dialog = new DrawingBoardDialog(context, new DrawingBoardDialog.DrawBoarDialogListener() {
                        @Override
                        public void onClear() {}
                        @Override
                        public void onFile(LocalMedia localMedia) {
                            ModeFormFile fileMode = writeFormClass.getFileMode(context,localMedia);
                            LogUtils.d("原始名称：" + fileMode.url);
                            fileMode.url = fileMode.url.replace(localMedia.getFileName(),"sx.jpg");
                            LogUtils.d("替换后名称：" + fileMode.url);
                            uploadFileMode(context, fileMode, new UpLoadFileListener() {
                                @Override
                                public void onComplete(ModeFormFile formImageMode, File file, LocalMedia localMedia) {
                                    formFileModeList.clear();
                                    formFileModeList.add(fileMode);
                                }
                            });
                        }
                        @Override
                        public void onBitMap(Bitmap bitmap) {
                            imageView.post(() -> {
                                imageView.setVisibility(View.VISIBLE);
                                imageView.setImageBitmap(bitmap);
                            });
                        }
                        @Override
                        public void onCancel() {}
                    });
                    dialog.show();
                }
            }
        });

        return writeFormClass.view;
    }


    private void uploadFileMode(Context context , ModeFormFile fileMode, UpLoadFileListener upLoadFileListener){
        String realPath = fileMode.path;
        String fileName = fileMode.url;

        COS.getInstance().uploadFile(context, FormBuilder.BUCKET_NAME, fileName, realPath, null, new CosUploadCallBack() {
            @Override
            public void onSleep(double v) {}
            @Override
            public void onComplete(String s) {
                upLoadFileListener.onComplete(fileMode,new File(fileMode.path),LocalMedia.generateLocalMedia(context,fileMode.path));
            }
            @Override
            public void onError(String s) {
                ToastUtils.showShort(s);
            }
        });
    }


    /**
     * 手写字段内容
     * 有权限也不允许修改
     * @param context
     * @param fullModel
     * @return
     */
    @Override
    protected View getShowFullView(Context context, FullClass fullModel) {
        //字段名属性设置
        fullModel.goneFieldNameView();
        //设置字段值
        fullModel.goneContentView();

        LoadImagesRecycler loadImagesRecycler = new LoadImagesRecycler(fullModel.getContext());

        loadImagesRecycler.getTitleView().getTvTitleView().setTextSize(fullModel.localConfig.field_name_text_size);
        loadImagesRecycler.getTitleView().getTvLeftTag().setBackgroundColor(fullModel.localConfig.leftColor);

        loadImagesRecycler.setMaxSum(fullModel.formField.getLittleNum());
//        loadImagesRecycler.setTag(fullModel.formField.getHint());
        loadImagesRecycler.setTitleName(fullModel.formField.getName());
        loadImagesRecycler.setMode(LoadImagesRecycler.NETWORK);
        List<ModeFormFullFileData> formFullFileDataList = fullModel.serverFullData.formFileModeMap.get(fullModel.formField.getId());
        if (formFullFileDataList != null) {
            List<MLocalMedia> mLocalMediaList = new ArrayList<>();
            for (ModeFormFullFileData formFullFileData : formFullFileDataList) {
                String fileUrl = COS.getInstance().getFileUrl(formFullFileData.bucket, formFullFileData.path);
                MLocalMedia mLocalMedia = MLocalMedia.generateHttpAsLocalMedia(fileUrl);
                mLocalMediaList.add(mLocalMedia);
            }
            loadImagesRecycler.setData(mLocalMediaList);
            loadImagesRecycler.show();
        }
        fullModel.addCustomControl(loadImagesRecycler);
        return fullModel.layout;
    }




    /**
     * 字段设置界面
     * @param context 上下文
     * @param installClass 配置
     * @return 1
     */
    @Override
    protected View getFieldInstallView(Context context, InstallClass installClass) {
        ObservableEmitter<ViewGroup> emitter = installClass.emitter;

        emitter.onNext(installClass.getIsMastView());        //是否必填
        emitter.onNext(installClass.getIsPrintView());        //是否参与打印

        return installClass.v;
    }

}
